#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>

int checkext(char * name, char * extension) {
	char * name_ext = strrchr(name, '.');
	if (!name_ext) {
		return 1;
	}
	if (strstr(extension, name_ext) != NULL) {
		return 0;
	}
	return 1;
}


int main(int argc, char ** argv) {
	char * path, * ext;
	if (!(path = getenv("PATH_TO_BROWSE")) || strcmp(path, " ") == 0) {
		path = (char *)malloc(sizeof(char));
		strcpy(path, ".");
	}
	ext = getenv("EXTENSION_TO_BROWSE");
	DIR * current = opendir(path);
	if (!current) {
		perror(path);
		return -1;
	}
	int vflag , wflag, i, status, count, child_count, proc_child_count, execret;
	vflag = wflag = 0;
	if (argc != 1) {
		for (i = 0; i < argc; i++) {
			if (strcmp(argv[i],"-w") == 0) {
				wflag = 1;
			} else if (strcmp(argv[i], "-v") == 0) {
				vflag = 1;
			}
		}
	}
	
	char * newpath, * name;
	struct dirent * d;
	pid_t pid;
	child_count = proc_child_count = count = 0;
	
	while ((d = readdir(current)) != NULL) {
		name = d->d_name;
		if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
			continue;
		}
		if (!ext || checkext(name, ext) == 0) {
			++count;
		}
		if (d->d_type == DT_DIR) {
			newpath = (char *)malloc(sizeof(char)*128);
			sprintf(newpath, "%s/%s", path, name);
			setenv("PATH_TO_BROWSE", newpath, 1);
			proc_child_count++;
			pid = fork();
			if (pid < 0) {
				perror("fork");
				exit(0);
			}
			if (pid == 0) {
				if (vflag == 1 && wflag == 1) {
					execret = execlp(argv[0], argv[0], "-v", "-w", NULL);
				} else {
					if (vflag == 1) {
						execret = execlp(argv[0], argv[0], "-v", NULL);
					} else if (wflag == 1) {
						execret = execlp(argv[0], argv[0], "-w", NULL);
					} else {
						execret = execlp(argv[0], argv[0], NULL);
					}
				}
				if (execret == -1) {
					perror("execlp");
					exit(-1);
				}
			}
		}
	}
	for (i = 0; i < proc_child_count; i++) {
		wait(&status);
		child_count += WEXITSTATUS(status);
	}
	if (vflag == 1) {
		printf("Ścieżka: %s\nIlośc plików: %d\nIlość plików w dzieciach: %d\n", path, count, child_count);
	}
	if (wflag == 1) {
		sleep(7);
	}
	exit(count + child_count);
	return 0;
}
